//
//  LCNetWork.m
//  LCPackage
//
//  Created by 马军凯 on 2021/6/22.
//  Copyright © 2021 龙采科技集团. All rights reserved.
//

#import "LCNetWork.h"
#import "SVProgressHUD+LCExtension.h" //挡板
#import "CrazyRequestSerialization.h"
#import "RBAccountManager.h"

static LCNetWork *NetWork = nil;
@implementation LCNetWork
+ (LCNetWork *)share {
    NetWork = [[LCNetWork alloc] init];
    return NetWork;
}

//get请求
+ (LCNetWork *)LCRequest_Get:(NSString *)header HUD:(BOOL)HUD parameters:(NSDictionary * _Nullable)parameters success:(RequestSuccessBlock)success fail:(RequestFailBlock)fail {
    //挡板
    if (HUD == YES) {
        [SVProgressHUD showWithGif];
    }
    //初始化
    LCNetWork *NetWork = [LCNetWork share];
    NetWork.block_fail = fail;
    NetWork.block_success = success;
    //代理方法
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    [config setHTTPAdditionalHeaders:nil];
    NetWork.manager = [NSURLSession sessionWithConfiguration:config delegate:NetWork delegateQueue:nil];
    //请求方法
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:header]];
    [request setHTTPMethod:@"GET"];
    [request setTimeoutInterval:requstTimeOut];
    //参数拼接
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
    if ([RBAccountManager getUserId].length) {
        [params setObject:[RBAccountManager getUserId] forKey:@"user_id"];
    }
    NSString *bodyStr = [LCNetWork requestBody:params];
    //参数中的+号改成%2B
    bodyStr = [LCNetWork HTMLfilter:bodyStr];
    //拼接
    request.URL = [NSURL URLWithString: [NSString stringWithFormat:@"%@?%@", header, bodyStr]];
    NSLog(@"请求头:%@",header);
    
    //请求
    __block NSURLSessionDataTask *task = [NetWork.manager dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //返回参数判断
        if (error == nil) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //json
            NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            //url
            NSString *url = [response.URL absoluteString];
            //异步
            if (NetWork.block_success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (HUD == YES) {
                        [SVProgressHUD dismiss];
                    }
                    NetWork.block_success(parameters,dict, url, json);
                });
            }
        } else {
            if (NetWork.block_fail) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (HUD == YES) {
                        [JKToast showWithText:@"连接服务器异常，请刷新重试"];
                        [SVProgressHUD dismiss];
                    }
                    NetWork.block_fail(error, [task.originalRequest.URL absoluteString]);
                });
            }
        }
    }];
    [task resume];
    
    return NetWork;
}
//post请求
+ (LCNetWork *)LCRequest_Post:(NSString *)header HUD:(BOOL)HUD parameters:(NSDictionary *)parameters success:(RequestSuccessBlock)success fail:(RequestFailBlock)fail {
    NSLog(@"=========================开始=========================");
    //挡板
    if (HUD == YES) {
        [SVProgressHUD showWithGif];
    }
    //初始化
    LCNetWork *NetWork = [LCNetWork share];
    NetWork.block_fail = fail;
    NetWork.block_success = success;
    //代理方法
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    [config setHTTPAdditionalHeaders:nil];
    NetWork.manager = [NSURLSession sessionWithConfiguration:config delegate:NetWork delegateQueue:nil];
    //请求方法
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:header]];
    [request setHTTPMethod:@"POST"];
    [request setTimeoutInterval:requstTimeOut];
    //参数拼接
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
    if ([RBAccountManager getUserId].length) {
        [params setObject:[RBAccountManager getUserId] forKey:@"user_id"];
    }
    NSString *bodyStr = [LCNetWork requestBody:params];
    //参数中的+号改成%2B
    bodyStr = [LCNetWork HTMLfilter:bodyStr];
    //拼接参数
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    //请求
    __block NSURLSessionDataTask *task = [NetWork.manager dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //判断返回的error
        if (error == nil) {
            //转换数据格式
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //json
            NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"接口返回的内容:%@", json);
            NSLog(@"=========================结束=========================");
            //url
            NSString *url = [response.URL absoluteString];
            if (NetWork.block_success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (HUD == YES) {
                        [SVProgressHUD dismiss];
                    }
                    NetWork.block_success(parameters,dic,url,json);
                });
            }
        } else {
            //返回失败
            if (NetWork.block_fail) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (HUD == YES) {
                        [JKToast showWithText:@"连接服务器异常，请刷新重试"];
                        [SVProgressHUD dismiss];
                    }
                    NetWork.block_fail(error,[task.originalRequest.URL absoluteString]);
                });
            }
        }
    }];
    [task resume];
    
    return NetWork;
}

//请求参数拼接
+ (NSString *)requestBody:(NSDictionary *)parameters {
    NSMutableString *bodyStr = [[NSMutableString alloc] init];
    for (int i = 0; i < parameters.allKeys.count; i++) {
        NSString *key = parameters.allKeys[i];
        if (parameters[key] == nil) {
            [bodyStr appendFormat:@"%@=%@", key, @""];
        } else {
            [bodyStr appendFormat:@"%@=%@", key, parameters[key]];
        }
        if (parameters.allKeys.count - 1 > i) {
            [bodyStr appendString:@"&"];
        }
    }
    
    return bodyStr;
}
//参数中的+号改成%2B
+ (NSString *)HTMLfilter:(NSString *)urlStr {

    NSMutableString *outputStr = [NSMutableString stringWithString:urlStr];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@"%2B"
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    return outputStr;
}


//文件流上传
+ (LCNetWork *)LCHttpFileUpload:(NSString *)headUrl HUD:(BOOL)HUD parameters:(NSDictionary *)parameters imageArr:(NSArray *)imageArr scale:(CGFloat)scale nameArr:(NSArray *)nameArr fileNameArr:(NSArray *)fileNameArr mimeType:(NSString *)mimeType success:(RequestSuccessBlock)success fail:(RequestFailBlock)fail {
    //挡板
    if (HUD == YES) {
        [SVProgressHUD showWithGif];
    }
    //初始化
    LCNetWork *netWork = [LCNetWork share];
    netWork.block_success = success;
    netWork.block_fail = fail;
    //代理方法
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    [config setHTTPAdditionalHeaders:nil];
    netWork.manager = [NSURLSession sessionWithConfiguration:config delegate:NetWork delegateQueue:nil];
    //尺寸
    if (scale > 1 || scale == 0) {
        scale = 0.5;
    }
    //上传图片
    NSMutableURLRequest *request = [[CrazyHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:headUrl parameters:parameters constructingBodyWithBlock:^(id<CrazyMultipartFormData> formData) {
        //处理数组
        if (imageArr.count != nameArr.count && imageArr.count != fileNameArr.count) {
            NSLog(@"文件名数组和后台数组和图片数组 数量不统一 ！！！！！");
            return ;
        }
        for (int i = 0; i < imageArr.count; i++) {
            UIImage *image = imageArr[i];
            NSString *name = nameArr[i];
            NSString *fileName = fileNameArr[i];
            
            if ([image isKindOfClass:[UIImage class]]) {
                NSData *imageData = UIImageJPEGRepresentation(image, scale);
                [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:mimeType];
            } else {
                NSData *data  = imageArr[i];
                [formData appendPartWithFileData:data name:name fileName:fileName mimeType:mimeType];
            }
        }
    } error:nil];
    //请求
    __block NSURLSessionUploadTask *dataTask = [netWork.manager uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //返回错误信息
        if (error == nil) {
            //转换数据格式
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //json
            NSString *json = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (HUD == YES) {
                    [SVProgressHUD dismiss];
                }
                netWork.block_success(parameters,dic, [response.URL absoluteString], json);
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (HUD == YES) {
                    [SVProgressHUD dismiss];
                }
                netWork.block_fail(error, [response.URL absoluteString]);
            });
        }
    }];
    
    [dataTask resume];
    
    return netWork;
}

@end
